<!-- 活动详情-选择报名人员 -->
<template>
  <a-drawer width="90%" :visible="visible" @close="closeModal">
    <template slot="title">
      <div class="disFlxAC">
        <div class="_mr-20">{{ title }}</div>
      </div>
    </template>
    <div class="disFlx">
      <div style="min-width:400px;width:400px" class=" _mr-10">
        <a-list
          item-layout="horizontal"
          :data-source="selectedRecords"
          bordered
          :pagination="{
            simple: true
          }"
        >
          <div slot="header" class="disFlxJS">
            <span>已选人员</span>
            <a-button type="danger" ghost @click="handleDelAll">
              全部删除
            </a-button>
          </div>

          <a-list-item slot="renderItem" slot-scope="item">
            <div @click="handleDel(item.id)" slot="actions">
              <a-icon type="close" />
            </div>
            <a-list-item-meta>
              <div slot="title" style="font-size:12px;white-space: nowrap;margin-right: 20px;">
                {{ item.userName || item.personName }}
              </div>
            </a-list-item-meta>
            <div style="font-size:12px">{{ item.companyName }}</div>
          </a-list-item>
        </a-list>
      </div>
      <div style="flex:1;">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="12" :xxl="6">
              <a-form-item label="关键词">
                <a-input v-model="queryParam.keyWord" placeholder="姓名、单位、会员职务、手机号搜索" allowClear />
              </a-form-item>
            </a-col>
            <a-col :md="12" :xxl="6">
              <a-form-item label="报名人员类型">
                <a-select
                  v-model="queryParam.identity"
                  placeholder="请选择报名人员类型"
                  allowClear
                  style="width: 150px;"
                >
                  <a-select-option
                    v-for="dict in Dict.getLocal('identityDict')"
                    :key="dict.dictValue"
                    :value="dict.dictValue"
                  >
                    {{ dict.dictLabel }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :xxl="6">
              <a-form-item label="报名类型">
                <a-select v-model="queryParam.activityTicketId" placeholder="报名类型" allowClear style="width: 150px;">
                  <a-select-option v-for="item in ticketList" :key="item.value" :value="item.id">
                    {{ item.ticketName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :xxl="6">
              <a-form-item label="报名来源">
                <a-select
                  v-model="queryParam.registerType"
                  placeholder="请选择报名来源"
                  allowClear
                  style="width: 150px;"
                >
                  <a-select-option v-for="item in registerTypeList" :key="item.value" :value="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col v-if="!approvalStatus" :md="12" :xxl="6">
              <a-form-item label="报名状态">
                <a-select
                  v-model="queryParam.approvalStatus"
                  placeholder="请选择报名状态"
                  allowClear
                  style="width: 150px;"
                >
                  <a-select-option
                    v-for="dict in Dict.getLocal('rosterApprovalStatusDict')"
                    :key="dict.dictValue"
                    :value="dict.dictValue"
                  >
                    {{ dict.dictLabel }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :xxl="6">
              <a-form-item label="签到状态">
                <a-select v-model="queryParam.signStatus" placeholder="请选择签到状态" allowClear style="width: 150px;">
                  <a-select-option v-for="item in signStatusOptions" :key="item.value" :value="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- <a-col :md="12" :xxl="6">
              <a-form-model-item label="会员职务">
                <a-select
                  v-model="queryParam.levelIds"
                  placeholder="请选择会员职务"
                  mode="multiple"
                  allowClear
                  :showArrow="true"
                  style="width: 150px"
                >
                  <a-select-option v-for="item in memberLevels" :value="item.id" :key="item.id"
                    >{{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col> -->
            <a-col :md="12" :xxl="6">
              <a-form-item label="参会者标签">
                <a-select
                  v-model="queryParam.labelIds"
                  mode="multiple"
                  placeholder="请选择参会者标签进行筛选"
                  allowClear
                  style="width: 150px;"
                >
                  <a-select-option v-for="item in label_list" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col v-if="activityInfo.activityType !== activityTypeEnum.other_join" :md="12" :xxl="6">
              <a-form-item label="来源组织">
                <a-select
                  v-model="queryParam.sourceTenantId"
                  placeholder="请选择来源组织"
                  allowClear
                  style="width: 150px;"
                >
                  <a-select-option v-for="item in organizationList" :key="item.tenantId" :value="item.tenantId">
                    {{ item.orgName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="12" :xxl="6">
              <a-form-item label="手机号为空">
                <a-checkbox v-model="isNullPhone"></a-checkbox>
              </a-form-item>
            </a-col>
            <a-col :sm="12">
              <a-form-item label="信息收集表">
                <SelectCustomForm :activityId="activityId" ref="SelectCustomForm" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :xxl="6">
              <a-button type="primary" @click="refresh">查询</a-button>
              <a-button @click="handleReset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>

        <div class="_pb-10 _pt-10 disFlxJS">
          <div>
            <span class="_mr-10 color9"
              >已勾选<span class="colorZS _pl-2 _pr-2 fw-7">{{ selectCount }}</span
              >位报名人员</span
            >
            <a-button v-if="total" type="primary" ghost @click="checkedAllMemberList"
              >{{ isAllChecked ? '取消勾选' : '勾选' }}"筛选条件"下全部<span class="fw-7 _pl-2 _pr-2">{{ total }}</span
              >位报名人员</a-button
            >
          </div>
        </div>

        <s-table
          ref="table"
          rowKey="id"
          :columns="columns"
          :data="loadData"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            onSelect: onSelect,
            onSelectAll: onSelectAll,
            getCheckboxProps: getCheckboxProps
          }"
          :scroll="{ y: 500 }"
        >
          <!-- 序号 -->
          <span slot="serial" slot-scope="text, record, index">
            {{ (pagination.current - 1) * pagination.pageSize + parseInt(index) + 1 }}
          </span>
          <!-- 参会者信息 -->
          <div slot="personInfo" slot-scope="text, record">
            <div>{{ record.personName }}</div>
            <div>{{ record.personTel }}</div>
          </div>
          <!-- 单位信息 -->
          <div slot="companyInfo" slot-scope="text, record">
            <a-tooltip :title="record.companyName">
              <div class="w-[200px] ov-1">{{ record.companyName }}</div>
            </a-tooltip>
            <div v-if="record.companyPosition" class="companyInfoTag">{{ record.companyPosition }}</div>
          </div>
          <!--签到信息-->
          <span slot="signInfo" slot-scope="text, record">
            <div>
              {{ signOperatorAndCheckType(record['signType']) }}
            </div>
            <div>
              {{ record['signTime'] }}
            </div>
          </span>
          <!-- 来源组织信息 -->
          <div slot="sourceInfo" slot-scope="text, record">
            <a-tooltip :title="record.orgName">
              <div class="w-[120px] ov-1">{{ record.orgName }}</div>
            </a-tooltip>
            <a-tag v-if="!record.identity">非会员</a-tag>
            <a-tooltip v-else :title="record.memberLevelName">
              <a-tag color="orange">
                <div class="ov-1">{{ record.memberLevelName }}</div>
              </a-tag>
            </a-tooltip>
          </div>
          <!-- 报名类型 -->
          <div slot="registerType" slot-scope="text">
            {{ RegisterTypeEnum[text] }}
          </div>
          <!-- 状态 -->
          <span slot="approvalStatus" slot-scope="text, record">
            <DictTag :options="Dict.getLocal('rosterApprovalStatusDict')" :value="record.approvalStatus" />
          </span>
        </s-table>
      </div>
    </div>

    <div
      v-if="visible"
      :style="{
        position: 'absolute',
        bottom: 0,
        padding: '10px 16px',
        textAlign: 'right',
        right: 0
      }"
    >
      <a-button style="margin-right: 8px" @click="closeModal">
        取消
      </a-button>
      <a-button
        v-if="rejectText"
        class="_mr-10"
        type="danger"
        @click="() => handleSubmit(ActionType.REJECTED)"
        :confirmLoading="confirmLoading"
      >
        {{ rejectText }}
      </a-button>
      <a-button type="primary" @click="() => handleSubmit(ActionType.APPROVED)" :confirmLoading="confirmLoading">
        {{ okText }}
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import { STable } from '@/components'
import { debounce } from '@/utils/common'
import DictTag from '@/components/DictTag'
import SelectCustomForm from '@/components/selectCustomForm'
import { getActivityOrganization, getTicketList, getActivityLabelList } from '@/api/activity/activity'
import { DataSourceEnum } from '@/enums/member'
import { signStatusEnum, activityTypeEnum, RegisterTypeEnum, RefundApprovalStatusEnum } from '@/enums/activity'
import { memberLevelGetDownList,  } from '@/api/system/system'
export const ActionType = {
  APPROVED: 'APPROVED',
  REJECTED: 'REJECTED'
}
export default {
  components: {
    STable,
    DictTag,
    SelectCustomForm
  },
  data() {
    return {
      DataSourceEnum,
      activityTypeEnum,
      RegisterTypeEnum,
      visible: false,
      ActionType,
      // 查询参数
      activityInfo: {},
      activityId: undefined,
      signStatusOptions: [
        { text: '已签到', value: signStatusEnum.END },
        { text: '未签到', value: signStatusEnum.STAY }
      ],
      api: {
        apiList: null,
        apiIdList: null,
        apiIdSearchList: null,
        submit: null
      },
      disabledFn: null,
      rejectText: '',
      okText: '',
      title: '',

      // 审核表单
      columns: [
        { title: '序号', scopedSlots: { customRender: 'serial' }, width: 60 },
        { title: '参会者信息', scopedSlots: { customRender: 'personInfo' }, width: 120 },
        { title: '单位信息', scopedSlots: { customRender: 'companyInfo' }, width: 200 },
        {
          title: '来源组织信息',
          scopedSlots: { customRender: 'sourceInfo' },
          width: 120
        },
        {
          title: '签到信息',
          width: 220,
          scopedSlots: { customRender: 'signInfo' }
        },
        { title: '状态', scopedSlots: { customRender: 'approvalStatus' }, width: 100 },
        {
          title: '报名类型',
          dataIndex: 'registerType',
          scopedSlots: { customRender: 'registerType' },
          width: 150
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10
      },
      total: 0,
      loadData: parameter => {
        this.pagination.current = parameter.current
        this.pagination.pageSize = parameter.pageSize
        return this.api
          .apiList(
            Object.assign(parameter, this.queryParam, {
              activityId: this.activityId,
              isNullPhone: this.queryParam.isNullPhone,
              signStatus: this.signStatus === undefined ? this.queryParam.signStatus : this.signStatus,
              approvalStatus: this.approvalStatus || this.queryParam.approvalStatus,
              orderByColumn: this.approvalStatus ? 'createTime' : this.signStatus ? 'signTime' : ''
            })
          )
          .then(res => {
            this.firstLoad = true
            this.total = res.data.total
            res.data.records.forEach(v => {
              this.disabledFn(v)
            })
            return res
          })
      },
      queryParam: {
        keyWord: undefined,
        levelId: undefined,
        registerType: undefined,
        approvalStatus: undefined,
        identity: undefined,
        signStatus: undefined,
        labelIds: [],
        isNullPhone: 0,
        sourceTenantId: undefined
      },
      approvalStatus: undefined,
      signStatus: undefined,
      selectedRowKeys: [],
      selectedRecords: [],
      label_list: [],
      memberLevels: [],
      organizationList: [],
      isAllChecked: false,
      confirmLoading: false,
      ticketList: []
    }
  },
  inject: ['drd'],
  watch: {},
  computed: {
    isNullPhone: {
      get() {
        return this.queryParam.isNullPhone === 1
      },
      set(val) {
        this.queryParam.isNullPhone = val ? 1 : 0
      }
    },
    downList() {
      return this.drd()
    },
    selectCount() {
      return this.selectedRecords.filter(f => !this.disabledFn(f)).length
    },
    registerTypeList() {
      let list = []
      Object.keys(RegisterTypeEnum).forEach(k => {
        list.push({
          text: RegisterTypeEnum[k],
          value: k
        })
      })
      return list
    }
  },
  mouted() {},
  methods: {
    async memberLevel() {
      let res = await memberLevelGetDownList()
      this.memberLevels = res.data || []
    },
    signOperatorAndCheckType(text) {
      const checkType = this.Dict.getLocal('CheckTypeEnumDict').find(item => item.dictValue == text)
      if (!checkType) return ''
      return checkType.dictLabel
    },
    debounce,
    getOrganizationList() {
      getActivityOrganization(this.activityId).then(res => {
        this.organizationList = res.data
      })
    },
    handelTicketListDownList() {
      return getTicketList(this.activityId).then(res => {
        if (res.code === 0) {
          this.ticketList = res.data || []
        }
      })
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.disabled,
          defaultChecked: record.isRegister == 1,
          name: record.name
        }
      }
    },
    moduleShow({
      row,
      apiList,
      apiIdList,
      apiIdSearchList,
      submit,
      disabledFn,
      okText,
      title,
      approvalStatus,
      signStatus,
      rejectText
    }) {
      this.isAllChecked = false
      this.activityInfo = row
      this.activityId = row.id
      this.selectedRowKeys = []
      this.selectedRecords = []
      this.visible = true
      this.api.apiList = apiList
      this.api.apiIdList = apiIdList
      this.api.apiIdSearchList = apiIdSearchList
      this.api.submit = submit
      this.disabledFn = disabledFn
      this.rejectText = rejectText
      this.okText = okText
      this.signStatus = signStatus
      this.approvalStatus = approvalStatus
      this.title = title
      this.handelTicketListDownList()
      this.getOrganizationList()
      this.getLabelList()
      this.memberLevel()
      this.refresh(true)
    },

    getLabelList() {
      getActivityLabelList(this.activityId).then(res => {
        this.label_list = res.data
      })
    },
    handleReload() {
      this.$refs.table.refresh()
    },
    //表格数据选中
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelect(record, selected) {
      if (selected) this.selectedRecords.push(record)
      else this.selectedRecords = this.selectedRecords.filter(f => f.id != record.id)
    },
    onSelectAll(selected, _, changeRows) {
      if (selected) this.selectedRecords.push(...changeRows)
      else {
        const ids = changeRows.map(item => item.id)
        this.selectedRecords = this.selectedRecords.filter(f => !ids.includes(f.id))
      }
    },
    handleDel(id) {
      this.selectedRecords = this.selectedRecords.filter(f => id !== f.id)
      this.selectedRowKeys = this.selectedRowKeys.filter(item => id !== item)
    },
    handleDelAll() {
      this.selectedRecords = []
      this.selectedRowKeys = []
      this.isAllChecked = false
    },

    async checkedAllMemberList() {
      this.handleReload() // 刷新表格禁用条件

      if (this.isAllChecked) {
        this.handleDelAll()
        return
      }

      const res = await this.api.apiIdList({
        ...this.queryParam,
        activityId: this.activityId,
        isNullPhone: this.queryParam.isNullPhone ? 1 : 0,
        signStatus: this.signStatus === undefined ? this.queryParam.signStatus : this.signStatus,
        approvalStatus: this.approvalStatus || this.queryParam.approvalStatus,
        orderByColumn: this.approvalStatus ? 'createTime' : this.signStatus ? 'signTime' : ''
      })

      if (res.code) throw new Error('查询当前搜索条件得人员id失败')
      if (!res.data || !res.data.ids || !res.data.ids.length) {
        throw new Error('当前搜索条件没有查到id')
      }
      this.selectedRowKeys = res.data.ids

      const rowsRes = await this.api.apiIdSearchList({
        activityId: this.activityId,
        registerIds: this.selectedRowKeys
      })

      if (rowsRes.code) throw new Error('查询当前搜索条件得人员信息失败')
      console.log(rowsRes)

      this.selectedRecords = rowsRes.data
      this.isAllChecked = true
    },
    async handleSubmit(type) {
      try {
        this.confirmLoading = true
        await this.api.submit(this.selectedRecords, type)
      } catch (error) {
      } finally {
        this.confirmLoading = false
      }
    },
    closeModal() {
      this.visible = false
      this.restFields()
      document.body.style.overflowY = 'auto'
      setTimeout(() => {
        this.$nextTick(() => {
          document.body.style.overflowY = 'auto'
        })
      }, 600)
    },

    restFields() {
      Object.keys(this.queryParam).forEach(k => {
        this.queryParam[k] = undefined
      })
    },
    refresh(isRefresh = false) {
      this.$nextTick(() => {
        const customFormItem = this.$refs.SelectCustomForm.getQueryParams()
        this.$set(this.queryParam, 'itemId', customFormItem ? customFormItem.itemId : undefined)
        this.$set(this.queryParam, 'itemAnswerId', customFormItem ? customFormItem.itemAnswerId : undefined)
        this.$set(this.queryParam, 'itemValue', customFormItem ? customFormItem.itemValue : undefined)
        this.$refs.table.refresh(isRefresh)
      })
    },
    handleReset() {
      this.restFields()
      this.$refs.table.refresh(true)
      this.$refs.SelectCustomForm.resetData()
    }
  }
}
</script>

<style>
.ant-list-item-action {
  margin-left: 0;
}
</style>
